package persistence.sqlsession;

import persistence.bean.Configuration;
import persistence.bean.MappedStatement;
import persistence.config.BoundSql;
import persistence.utils.GenericTokenParser;
import persistence.utils.ParameterMapping;
import persistence.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SampleExecutor implements Executor {
    public <E> List<E> query(Configuration configuration, MappedStatement statement, Object... params) throws Exception {
        // 1.获取连接
        Connection connection = configuration.getDataSource().getConnection();
        String sql = statement.getSql();
        // 2.解析sql
        BoundSql boundSql = getBoundSql(sql);
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMapping();
        // 3.设置参数
        // 3.1.获取参数全路径
        String parameterClassName = statement.getParameterType();
        Class<?> parameterClass = getClassType(parameterClassName);
        for (int i = 0; i < parameterMappings.size(); i++) {
            ParameterMapping parameterMapping = parameterMappings.get(i);
            String content = parameterMapping.getContent();
            // 3.2.反射
            Field declaredField = parameterClass.getDeclaredField(content);
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[i]);
            preparedStatement.setObject(i + 1, o);
        }
        // 4.执行SQL
        ResultSet resultSet = preparedStatement.executeQuery();
        // 5.映射实体
        String resultClassName = statement.getResultType();
        Class<?> resultClass = getClassType(resultClassName);

        List<Object> result = new ArrayList<Object>();
        while (resultSet.next()) {
            Object instance = resultClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i < metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(instance, value);
            }
            result.add(instance);
        }


        return (List<E>) result;
    }

    private Class<?> getClassType(String parameterClassName) throws ClassNotFoundException {
        if (parameterClassName != null && parameterClassName.length() > 0) {
            Class<?> aClass = Class.forName(parameterClassName);
            return aClass;
        }
        return null;
    }

    /***
     * 解析 sql
     * @param sql
     * @return
     */

    private BoundSql getBoundSql(String sql) {
        // 根据标记解析器处理sql占位
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        // 替换了 #{id} 的sql
        String parseSql = genericTokenParser.parse(sql);
        // 解析出来的参数
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parseSql, parameterMappings);
    }
}
